package reflection;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * Created with IntelliJ IDEA
 * Description:通过反射操作属性学习
 * User:22954
 * Date:2024-04-17
 * Time:14:37
 */
public class ReflecAccessProperty {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class<?> cls = Class.forName("reflection.User");
        Object o = cls.getDeclaredConstructor().newInstance();

        Field age = cls.getDeclaredField("age");
        age.setAccessible(true);
        age.set(o,30);
        System.out.println(o);//User{name='Jack', age=30}

        Field id = cls.getDeclaredField("id");
        id.setAccessible(true);
        id.set(o,"123456");
        System.out.println(id.get(o));//123456
        id.set(null,"987654");//静态属性属于类,与对象无关 null为默认当前类
        System.out.println(id.get(null));//987654
    }
}
